<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 登陆 -->
    <van-form @submit="loginFn">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入您的手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { getLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',

  data() {
    return {
      mobile: '',
      code: '',
      rules: {
        mobile: [
          // 必填项
          { required: true, message: '请填写手机号' },
          // 正则校验手机号格式
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
        ],
        code: [
          // 必填项
          { required: true, message: '请填写验证码' },
          // 正则校验手机号格式
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      }
    }
  },

  methods: {
    ...mapMutations('user', ['setToken']),
    async loginFn() {
      console.log('发送中')
      try {
        // 发送请求
        const res = await getLogin(this.mobile, this.code)
        console.log(res)
        // 将token存储在vuex中
        this.setToken(res.data)
        // 弹框 this.$totast
        this.$toast.success('登录成功')
        // 登录成功后跳转页面到首页
        this.$router.push('/')
      } catch (e) {
        this.$toast.fail('登陆失败')
        console.log(e)
      }
    }
  }
}
</script>

<style></style>
